package org.domeos.framework.shiro.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.servlet.AbstractFilter;
import org.domeos.framework.engine.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IdCenterFilter extends AbstractFilter{

	private static Logger logger = LoggerFactory.getLogger(IdCenterFilter.class);
	
	//登录失败时默认返回401状态码
    private void onLoginFail(ServletResponse response) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.getWriter().write("{'result':'','resultCode':401,'resultMsg':'login fail!'}");
    }

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String token = req.getHeader("token");
		if(StringUtils.isEmpty(token)){
			logger.info("IdCenterFilter token is null!");
			onLoginFail(response);
			return;
		}
		String userId = RedisUtil.getStringRedisTemplate().opsForValue().get(token);
		if(StringUtils.isEmpty(userId)){
			logger.info("IdCenterFilter cache userId is null!");
			onLoginFail(response);
			return;
		}
		req.setAttribute("userId", userId);
		chain.doFilter(request, response);
	}
}
